package com.service.gmall.Item.lock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author alpha
 * @className: RedisDistLock
 * @Description: 实现redis的分布式锁
 */
@Service
public class RedisDistLock {
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 加锁
     * @return
     */
    public String lock(){
        String token = UUID.randomUUID().toString();
        //加锁，采用自旋锁，保证每个线程都能拿到锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token, 10, TimeUnit.MINUTES);
        while (!lock){
            //自旋去
        }
        return token;
    }

    /**
     * 解锁
     */
    public void unlock(String token){
        String luaScript = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        redisTemplate.execute(new DefaultRedisScript<>(luaScript,Long.class), Arrays.asList("lock"),token);
    }
}
